import logging
from datetime import datetime

from app.models.problem import Problem

"""
根据用户id查询题目
"""
def get_problem_list_by_author(author_id):
    try:
        problems = Problem.query.filter_by(creator_id=author_id).all()
        problem_list = []
        for problem in problems:
            problem_dict = problem.to_dict()
            problem_list.append(problem_dict)
        return problem_list
    except Exception as e:
        logging.error(e)
        return None

"""
新增题目
"""
def create_problem_by_author(data):
    try:
        problem = Problem(
            title=data['title'],
            requirement=data['requirement'],
            content=data['content'],
            difficulty=data['difficulty'],
            creator_id=data['creator_id']
        )
        problem.save()
        return problem.to_dict()
    except Exception as e:
        logging.error(e)
        return None

"""
新增题目
"""
def update_problem_by_id(data):
    try:
        problem = Problem.query.filter_by(id=data['id']).first()
        problem.title = data['title']
        problem.requirement = data['requirement']
        problem.content = data['content']
        problem.difficulty = data['difficulty']
        problem.update_time = datetime.utcnow()
        problem.save()
        return problem.to_dict()
    except Exception as e:
        logging.error(e)
        return None

"""
删除题目
"""
def delete_problem_by_id(problem_id):
    try:
        problem = Problem.query.filter_by(id=problem_id).first()
        problem.delete()
        return True
    except Exception as e:
        logging.error(f"删除题目失败:{str(e)}")
        return False
